﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BeIT.MemCached;
using DevToolBox.Common;
using DevToolBox.Cloud.Common;

namespace DevToolBox.Cloud.Amazon
{
    /// <summary>
    /// Class to access a Memcached based distributed cache using BeIT
    /// </summary>
    public class MemCachedTransactions : ICacheable
    {
        private MemcachedClient cache = null;
        private DateTime expirity;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="logger">Logger object</param>
        public MemCachedTransactions()
        {
            string memCachedUrl = ConfigParamReader.GetString("MemCachedUrl");
            MemcachedClient.Setup("MyCache", new string[] { memCachedUrl });
            cache = MemcachedClient.GetInstance("MyCache");
            cache.SendReceiveTimeout = 5000;
            cache.ConnectTimeout = 5000;
            cache.MinPoolSize = 1;
            cache.MaxPoolSize = 5;

            int daysToStoreCacheItems = ConfigParamReader.GetInt32("DaysToStoreCacheItems");
            expirity = DateTime.Now.AddDays(daysToStoreCacheItems);
        }

        /// <summary>
        /// Method to write an item into the cache
        /// </summary>
        /// <param name="key">Item key</param>
        /// <param name="value">Item value</param>
        public void Set(string key, object value)
        {
            try
            {
                if (cache != null && key != null)
                {
                    if (value == null)
                    {
                        cache.Delete(key);
                    }
                    else
                    {                        
                        cache.Set(key, value, expirity);
                    }
                }                
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// Method to get an item from the cache
        /// </summary>
        /// <param name="key">Item key</param>
        /// <returns>Item value</returns>
        public object Get(string key)
        {
            if (cache == null || key == null) return null;
            object retVal = cache.Get(key);
            return retVal;
        }
    }
}